<template>
  <div id="cart">
    <Header></Header>
    <section class="jarallax py-5">
      <div class="jarallax-bg"></div>
      <div class="hero-content py-0 py-md-5">
        <div class="d-flex flex-column d-md-block align-items-center">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item>首页</el-breadcrumb-item>
            <el-breadcrumb-item>页面</el-breadcrumb-item>
            <el-breadcrumb-item>购物车</el-breadcrumb-item>
          </el-breadcrumb>
          <h1>购物车</h1>
        </div>
      </div>
    </section>
    <div class="container-lg">
      <el-row :gutter="20">
        <el-col :md="16">
          <el-table :data="cartItems" class="custom-table">
            <el-table-column
              prop="product"
              label="产品"
              width="350"
              class-name="custom-font-size"
            >
              <template slot-scope="scope">
                <div class="cart-info d-flex align-items-center mb-4">
                  <div class="col-lg-3">
                    <div class="card-image">
                      <img
                        :src="imgs(scope.row.foodlist.foodImg)"
                        alt="product name"
                        class="img-fluid"
                      />
                    </div>
                  </div>
                  <div class="col-lg-9">
                    <div class="card-detail ps-3">
                      <a
                        :href="scope.row.link"
                        class="text-decoration-none"
                        :title="scope.row.cartFoodname"
                        >{{ scope.row.cartFoodname }}</a
                      >
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="quantity"
              label="数量"
              width="280"
              class-name="custom-font-size"
            >
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.quantity"
                  :min="1"
                  :max="10"
                  size="small"
                ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column
              prop="subtotal"
              label="小计"
              width="260"
              class-name="custom-font-size"
            >
              <template slot-scope="scope">
                <span class="money text-dark"
                  >${{ subtotal(scope.row).toFixed(2) }}</span
                >
              </template>
            </el-table-column>
            <el-table-column width="80" class-name="custom-font-size">
              <template slot-scope="scope">
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  @click="removeItem(scope.$index)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
          <div>
            <el-pagination
              layout="prev, pager, next"
              :current-page="currentPages"
              :page-size="pageSize"
              :total="total"
              @current-change="currentChange"
            >
            </el-pagination>
          </div>
        </el-col>

        <el-col :md="8">
          <div class="cart-totals custom-total-style">
            <h4 class="pb-4">购物车总计</h4>
            <div class="total-price pb-5">
              <el-descriptions
                title=""
                :column="1"
                borderPricetotals
                class="no-side-borders"
              >
                <el-descriptions-item label="总计"
                  >${{ Pricetotals }}</el-descriptions-item
                >
                <el-descriptions-item label="总数量">{{
                  totalQuantity
                }}</el-descriptions-item>
              </el-descriptions>
            </div>
            <div class="button-wrap row g-2">
              <el-button
                type="primary"
                class="custom-black-button"
                @click="updateCartAndPaginate"
              >
                更新购物车
              </el-button>
              <el-button type="primary" class="custom-black-button"
                >继续购物</el-button
              >
              <el-button type="success" class="w-100">
                <router-link
                  to="/checkout"
                  style="text-decoration: none; color: white"
                  >继续结账</router-link
                >
              </el-button>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    <section class="pb-4 my-4">
      <div>
        <el-card shadow="always" class="rounded-5 bg-warning">
          <div class="yingyong">
            <el-row>
              <el-col :md="6" class="yrow">
                <h2 class="mt-5">下载有机应用程序</h2>
                <p class="mb-3">在线订单变得简单、快速和可靠</p>
                <div class="gap-2 mb-5">
                  <a href="#" title="App store"
                    ><img
                      src="../images/img-app-store.png"
                      alt="app-store"
                      class="img-fluids"
                  /></a>
                  <a href="#" title="Google Play"
                    ><img src="../images/img-google-play.png" alt="google-play"
                  /></a>
                </div>
              </el-col>
              <el-col :md="5">
                <img
                  src="../images/banner-onlineapp.png"
                  alt="phone"
                  class="img-phone"
                />
              </el-col>
            </el-row>
          </div>
        </el-card>
      </div>
    </section>
    <div>
      <section>
        <div class="people-section">
          <h2 class="my-5">人们也在寻找</h2>
          <a href="#">蓝钻石杏仁</a>
          <a href="#">Angie的玉米片</a>
          <a href="#">咸角玉米</a>
          <a href="#">Chobani希腊酸奶</a>
          <a href="#">甜香草酸奶</a>
          <a href="#">Foster Farms 外带 脆皮鸡翅</a>
          <a href="#">勇士混合有机</a>
          <a href="#">潮芝士奶油</a>
          <a href="#">鸡肉丸</a>
          <a href="#">蓝钻石杏仁</a>
          <a href="#">Angie的玉米片</a>
          <a href="#">咸角玉米</a>
          <a href="#">Chobani希腊酸奶</a>
          <a href="#">甜香草酸奶</a>
          <a href="#">Foster Farms 外带 脆皮鸡翅</a>
          <a href="#">勇士混合有机</a>
          <a href="#">潮芝士奶油</a>
          <a href="#">鸡肉丸</a>
        </div>
      </section>

      <section class="py-6">
        <div>
          <el-row :gutter="20">
            <el-col
              :xs="12"
              :sm="6"
              :md="5"
              :lg="4"
              class="border-width"
              v-for="(service, index) in services"
              :key="index"
            >
              <el-card shadow="hover" class="border-dark-subtle">
                <div class="text-dark mb-3">
                  <img :src="imgs(service.icon)" />
                </div>
                <div class="card-body">
                  <h5>{{ service.title }}</h5>
                  <p class="card-text">{{ service.description }}</p>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </section>
    </div>
    <Footer></Footer>
  </div>
</template>
<script>
import Header from "./header.vue";
import Footer from "../pages/footer.vue";
import { PageCart, deleteCart } from "../api/api";

export default {
  name: "cart",
  components: {
    Header,
    Footer,
  },
  data() {
    return {
      cartItems: [],
      services: [
        {
          icon: "arcticons.svg",
          title: "免费送货",
          description: "Lorem ipsum dolor sit amet, consectetur adipi elit.",
        },
        {
          icon: "secureTan.svg",
          title: "100% 安全支付",
          description: "Lorem ipsum dolor sit amet, consectetur adipi elit.",
        },
        {
          icon: "safetyOutlined.svg",
          title: "质量保证",
          description: "Lorem ipsum dolor sit amet, consectetur adipi elit.",
        },
        {
          icon: "ProiconsCheckmarkCircle.svg",
          title: "保证节省",
          description: "Lorem ipsum dolor sit amet, consectetur adipi elit.",
        },
        {
          icon: "BasilPresentOutline.svg",
          title: "每日优惠",
          description: "Lorem ipsum dolor sit amet, consectetur adipi elit.",
        },
      ],
      currentPages: 1,
      pageSize: 2,
      total: 0,
      Pricetotals: 0,
    };
  },
  computed: {
    subtotal() {
      return function (row) {
        // console.log(row, "!!!!!!!!!!!!!!!!~~");
        let nuumber = row.cartTotal * row.quantity;
        return nuumber;
      };
    },

    cartTotal() {
      // console.log(this.subtotal, "!!!!!!!");
      return this.subtotal;
    },
    imgs() {
      return function (imgName) {
        return require(`@/images/${imgName}`);
      };
    },
    totalQuantity() {
      console.log(this.cartItems, "cartItems");
      this.Pricetotals = this.cartItems
        .reduce((sum, item) => sum + item.subtotal, 0)
        .toFixed(2);
      return this.cartItems.reduce((sum, item) => sum + item.quantity, 0);
    },
  },
  watch: {
    cartItems: {
      handler(newValue) {
        newValue.forEach((item) => {
          item.subtotal = item.quantity * item.cartTotal;
        });
        this.updateTotals(); // 更新总价和总数量
      },
      deep: true, // 监听对象属性的变化
    },
  },

  methods: {
    proceedToCheckout() {
      // this.router.push("/checkout");
      // const cartData = this.cartItems.map((item) => ({
      //   // productName: item.cartFoodname,
      //   description: item.cartFoodname, // 这里假设简要描述就是商品名称
      //   subtotal: item.subtotal.toFixed(2),
      // }));
      // const totalPrice = this.Pricetotals;
      // this.$router.push({
      //   name: "Checkout",
      //   params: { cartData, totalPrice },
      // });
      const itemsWithQuantity = this.cartItems.map((item) => ({
        ...item,
        quantity: item.quantity, // 假设 item 对象中有 quantity 属性
      }));
      this.$router.push({
        cartFoodname: "Checkout",
        params: { items: itemsWithQuantity },
      });
    },
    removeItem(index) {
      if (index >= 0 && index < this.cartItems.length) {
        console.log("删除的项的索引：", this.cartItems[index].cartId);
        const itemId = this.cartItems[index].cartId; // 假设每项都有一个唯一的 id
        deleteCart(itemId) // 调用后端 API 删除记录
          .then(() => {
            this.cartItems.splice(index, 1); // 从本地数组中移除该项
            this.updateTotals(); // 更新总价和总数量
          })
          .catch((err) => {
            console.error("删除失败", err);
          });
      }
    },

    updateTotals() {
      this.Pricetotals = this.cartItems
        .reduce((sum, item) => sum + item.subtotal, 0)
        .toFixed(2);
      this.totalQuantity = this.cartItems.reduce(
        (sum, item) => sum + item.quantity,
        0
      );
    },
    updateCartAndPaginate() {
      // 重置每个商品的数量为1
      this.cartItems.forEach((item) => {
        item.quantity = 1;
        item.subtotal = item.quantity * item.cartTotal;
      });

      // 重新计算总价
      this.Pricetotals = this.cartItems
        .reduce((sum, item) => sum + item.subtotal, 0)
        .toFixed(2);
      // 重新查询数据以更新购物车并分页
      this.currentPages = 1;
      this.query(); // 调用查询方法以更新购物车并分页
    },
    query() {
      let cartId = -1;
      if (this.value != "" && this.value != -1) {
        cartId = this.value;
      }

      PageCart(this.currentPages, this.pageSize)
        .then((res) => {
          console.log(res);
          this.total = res.total;
          this.cartItems = res.list.map((item) => ({
            ...item,
            quantity: 1, // 初始化 quantity 为 1
            // 确保有 id 属性
            id: item.id || null, // 添加 id 属性，如果没有则设置为 null
            subtotal: item.quantity * item.cartTotal, // 初始化 subtotal
          }));
        })
        .catch((err) => {
          console.log(err);
        });
    },
    currentChange(e) {
      console.log("页码发生了变化", e);
      this.currentPages = e;
      this.query();
    },
  },
  mounted() {
    const jarallax = this.$el.querySelector(".jarallax");
    const jarallaxBg = this.$el.querySelector(".jarallax-bg");

    jarallax.addEventListener("mousemove", (event) => {
      const rect = jarallax.getBoundingClientRect();
      const x = event.clientX - rect.left;
      const y = event.clientY - rect.top;

      const offsetX = (x / rect.width - 0.5) * 50; // 调整偏移量
      const offsetY = (y / rect.height - 0.5) * 50; // 调整偏移量

      jarallaxBg.style.backgroundPosition = `${50 + offsetX}% ${50 + offsetY}%`;
    });

    jarallax.addEventListener("mouseleave", () => {
      jarallaxBg.style.backgroundPosition = "center";
    });
  },
  created() {
    this.query();
  },
};
</script>
<style scoped>
* {
  margin: 0;
  padding: 0;
}

.total-price .el-descriptions-item {
  font-size: 20px; /* 根据需要调整字体大小 */
}

.jarallax {
  position: relative;
  height: 400px; /* 设置图片容器的高度 */
  overflow: hidden;
}

.jarallax-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url("../images/banner-1.jpg");
  background-size: cover;
  background-position: center;
  transition: background-position 0.3s ease;
}

.hero-content {
  position: relative;
  z-index: 1; /* 确保文字在图片上面 */
  color: white; /* 根据图片颜色调整文字颜色 */
  text-align: center; /* 文字居中对齐 */
}

.d-md-block {
  font-size: 28px;
  margin-top: 150px;
  color: black;
  margin-left: 20px;
}

.el-breadcrumb {
  margin-bottom: 20px; /* 可选：增加间距 */
  font-size: 22px;
}

.d-md-block h1 {
  float: left;
  margin-left: 15px;
}

.people-section a {
  display: inline-block; /* 或者 block，根据需求选择 */
  width: 220px; /* 设置宽度 */
  height: 40px; /* 设置高度 */
  text-align: center;
  margin: 12px;
  border-color: #fcf7eb;
  background-color: #fcf7eb;
  color: #747474;
  text-decoration: none;
  line-height: 40px;
  margin-bottom: 0.5rem !important;
}

.people-section a:hover {
  border-color: #ffecbe;
  background-color: #ffecbe;
  color: #747474;
}

.cart-totals {
  width: 100%;
  margin-left: 20px;
}

.button-wrap .el-button {
  margin-bottom: 10px;
}

.container-lg {
  width: 92%;
  margin: 0 auto;
  margin-top: 50px;
  margin-bottom: 80px;
  /* border: 1px solid red; */
}

.custom-font-size {
  font-size: 20px;
  /* border: 2px solid greenyellow; */
}

.img-fluid {
  width: 107px;
  height: 120px;
}

.custom-table {
  width: 95%;
  /* margin-left: 14px; */
  padding-left: 10px;
  margin-right: 10px;
  /* border: 1px solid red; */
  position: relative;
}

.text-decoration-none {
  font-size: 22px;
  text-decoration: none;
  color: black;
}
.card-title {
  position: absolute;
  top: 60px;
  margin-left: 120px;
}
.pb-4 {
  font-size: 28px;
  margin-bottom: 40px;
}

.custom-total-style {
  font-size: 20px;
}

.no-side-borders {
  font-size: 20px;
  margin-bottom: 30px;
}
.no-side-borders .el-descriptions__table {
  border-left: none;
  border-right: none;
  border-top: 1px solid #ebeef5; /* 上横线 */
  border-bottom: 1px solid #ebeef5; /* 下横线 */
}

.custom-black-button {
  width: 40.5%;
  background-color: black; /* 设置背景颜色为黑色 */
  border-color: black; /* 设置边框颜色为黑色 */
  color: white; /* 设置文字颜色为白色 */
  font-size: 18px;
}

.button-wrap {
  position: relative;
}

.custom-black-button:hover {
  background-color: #fff; /* 设置鼠标悬停时的背景颜色 */
  border-color: #fff; /* 设置鼠标悬停时的边框颜色 */
}

.w-100 {
  width: 83%;
  position: absolute;
  left: -10px;
  top: 50px;
  font-size: 18px;
}

.w-100:hover {
  background-color: orange;
  border-color: orange;
}

.bg-warning {
  width: 92%;
  margin: 0 auto;
  background-color: #ffc107;
  border-radius: 30px;
}

.yingyong {
  position: relative;
}

.mt-5 {
  margin-top: 3rem;
}

.mb-3 {
  margin-top: 1rem;
  margin-bottom: 1rem;
  color: #666;
  font-size: 16px;
}

.yrow {
  width: 80%;
  position: absolute;
  left: 200px;
  margin-top: 100px;
  /* border: 1px solid red; */
  margin-left: 100px;
}

.img-fluids {
  margin-right: 10px;
}

.img-phone {
  margin-bottom: -25px;
  margin-left: 780px;
}

.people-section {
  width: 90%;
  margin: 0 auto;
  margin-top: 80px;
  margin-bottom: 80px;
  /* border: 1px solid black; */
  /* margin-left: 10px; */
}

.my-5 {
  margin-bottom: 20px;
  margin-left: 10px;
  /* border: 1px solid red; */
}

.me-2 {
  border-color: #fcf7eb;
  background-color: #fcf7eb;
  color: #747474;
  /* border: 2px solid greenyellow; */
  margin-top: 5px;
  margin-left: 10px;
}

.me-2:hover {
  border-color: #ffecbe;
  background-color: #ffecbe;
  color: #747474;
}

.me-1 {
  /* width: 14.5%; */
  /* text-align: center; 如果需要居中对齐文本 */
  border: 1px solid red;
  /* display: inline-block; 确保按钮根据内容自适应宽度 */
}

.py-6 {
  width: 90%;
  margin: 0 auto;
  margin-bottom: 80px;
}

.border-width {
  width: 20%;
}

.border-dark-subtle {
  border: 1px solid black;
  border-radius: 10px;
}

.card-body h5 {
  font-size: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
}

.card-text {
  color: #999;
  padding-bottom: 10px;
}

.flex-column {
  /* border: 1px solid red; */
  margin-left: 80px;
}

.card-detail {
  float: left;
  margin-left: 140px;
  margin-top: -80px;
}
</style>